<?php


namespace app\backend\controller\v2;

use app\backend\validate\GradeValidate;
use app\common\model\Grade as GradeModel;
use think\exception\ValidateException;
class Grade extends BaseController
{
    /**
     * 小学年级列表
     *
     * @return \think\Response
     */
    public function index()
    {
        // 年级表
        $where = input('title');
        // 分页、排序等
        $page = input('page/d', 1);
        $pageSize = input('pageSize/d', 10);
        //获取列表
        $list = GradeModel::order('id','asc')
            ->field('*')
            ->where(function ($query)use ($where){
                $query->where('title','like','%'.$where.'%');
            })->select();
        return sucessMsg(200, '获取成功！', ['list' => $list, 'total' => count($list), 'page' => $page, 'pageSize' => $pageSize]);
    }

    /**
     * 显示创建轮播表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $model = new GradeModel();
        $data = input();
        try {
            validate(GradeValidate::class)->scene('create')->check($data);
            if ($model->save($data)) {
                return sucessMsg(200, '创建成功！');
            }
            return errMsg(500, '创建失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(400, '请选择要修改的id！');
        }
        $data = input();
        try {
            validate(GradeValidate::class)->scene('update')->check($data);

            if (GradeModel::update($data, ['id' => $id])) {
                return sucessMsg(200, '修改成功！');
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(400, '请选择要删除数据id！');
        }
        $data = GradeModel::find($id);
        if (empty($data)){
            return errMsg(400, '要删除的数据为空！');
        }
        if (GradeModel::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(500, '删除失败！');
    }
}